"""
@Author：WangYuXiang
@E-mile：Hill@3io.cc
@CreateTime：2021/4/13 16:30
@DependencyLibrary：无
@MainFunction：无
@FileDoc： 
    group.py
    文件说明
@ChangeHistory:
    datetime action why
    example:
    2021/4/13 16:30 change 'Fix bug'
        
"""
from datetime import datetime

from common.auth.models import GroupModel
from common.auth.serializers import GroupModelSerializer
from common.utils.authentication import GeneralTokenAuthenticate
from srf.status import HttpStatus
from srf.views import APIView
from srf.viewsets import ModelViewSet


async def recursive_parent_group(groups) -> list:
    """递归得到父级组织机构权限"""
    group_list = []
    for group in groups:
        child = await group.child
        if child:
            child = await recursive_parent_group(child)
        group_dict = {
            'id': group.id,
            'label': group.name,
            'code': group.code,
            'children': [],
            'is_role': False,
            'parent_id': group.parent_id
        }
        roles = await group.roles.all().values('code', 'name', 'id', 'group_id')
        role_dict_list = []
        for role in roles:
            role['label'] = role.pop('name')
            role['parent_id'] = role.pop('group_id')
            role.update({'is_role': True, 'child': []})
            role_dict_list.append(role)
        group_dict['children'].extend(role_dict_list)
        group_dict['children'].extend(child)
        group_dict['children'].sort(key=lambda x: x["is_role"], reverse=False)
        group_list.append(group_dict)
    return group_list


async def recursive_group_user(groups) -> list:
    """递归得到父级组织下聘用的用户"""
    group_users = []
    for group in groups:
        child = await group.child
        if child:
            child_group_users = await recursive_group_user(child)
            group_users.extend(child_group_users)
        roles = await group.roles.all()
        for role in roles:
            users = await role.users.all().values('id', 'account', 'nickname', 'is_active', 'is_super_admin', 'login_datetime')
            for user in users:
                user['role'] = role.name
                user['group'] = group.name
                login_datetime = user.get('login_datetime', None)
                if isinstance(login_datetime, datetime):
                    user['login_datetime'] = login_datetime.strftime("%Y-%m-%d %H:%M:%S")
                group_users.append(user)
    return group_users


class GroupViewSet(ModelViewSet):
    """
    对应组织机构的增删改查功能

    :param ModelViewSet: ModelViewSet
    :return: [description]
    :rtype: [type]
    """
    queryset = GroupModel
    serializer_class = GroupModelSerializer
    authentication_classes = (GeneralTokenAuthenticate,)
    search_fields = ('@code',)

    async def list(self, request, *args, **kwargs):
        queryset = await self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        data = await serializer.data
        return self.success_json_response(data=data)


class GroupRoleTreeView(APIView):
    """
    组织机构及角色树形图

    :param APIView: APIView
    :return: [description]
    :rtype: [type]
    """
    authentication_classes = (GeneralTokenAuthenticate,)

    async def get(self, request, *args, **kwargs):
        top_groups = await GroupModel.filter(parent=None).all()
        tree = await recursive_parent_group(top_groups)
        return self.success_json_response(tree)


# TODO: 此处需要修改为能分页的，应使用SQL完成操作
class GroupEmployUserListView(APIView):
    """组织下聘任的用户列表"""
    authentication_classes = (GeneralTokenAuthenticate,)

    async def get(self, request, pk, *args, **kwargs):
        group = await GroupModel.get_or_none(id=pk)
        if not group:
            return self.error_json_response(msg='不存在资源%s' % pk, http_status=HttpStatus.HTTP_404_NOT_FOUND)
        users = await recursive_group_user([group])
        return self.success_json_response(users)
